import toast from '@/utils/toast'
import route from '@/utils/route'
import { get_access_token, setEnv } from '@/storage/global'
import { getUserInfo } from '@/storage/login'
import { admin_type } from '@/api/group/config'
import { server_type } from '@/api/server/config'
import { loginPage_index } from '@/route'

setEnv()
interface resType {
  Code: number
  Message: string
  Result: any
}

const handler_401 = function (platform: platform_type) {
  // 	当业务端的登录令牌过期时
  // 	wx小程序的getCode api只能在打开这次小程序时，最多请求请求两次此api获取用户code
  if (platform === 'admin') {
    toast.$toast('admin令牌过期, 正在跳转')
    //   这里过期了不能调用请求方法，因为循环引用了request
  } else if (platform === 'server') {
    toast.$toast('server令牌过期, 正在跳转')
  }

  setTimeout(() => {
    route.$route_redirect(loginPage_index)
  }, 1000)
}

const handler_WeAppLogin_4000 = function (
  Result: any,
  Code: number,
  Message: string
) {
  if (Code === 4000) {
    if (Result) {
      toast.$toast(Result)
    } else {
      if (Message) {
        const str = '用户绑定酒店失败！'
        if (
          Message.startsWith(str) &&
          Message.includes('{') &&
          Message.includes('}')
        ) {
          try {
            const parse_Message = JSON.parse(Message.split(str)[1]).Message
            toast.$toast(parse_Message)
          } catch (e) {
            console.log('解析Message错误', e)
          }
        } else {
          toast.$toast(Message)
        }
      } else {
        toast.$toast('其他登录错误')
      }
    }
  }
}

type platform_type = admin_type | server_type
type method_type = 'get' | 'post' | 'put' | 'delete' | 'DELETE'
function createRequest(
  baseURL: string,
  platform: platform_type,
  mergeHeaders?: Object
) {
  return ({
    url = '',
    method = 'get',
    data = {}
  }: {
    url: string
    method?: method_type
    data?: any
  }) => {
    return new Promise((resolve, reject) => {
      let headers = {}

      const access_token: string = get_access_token()
      if (access_token) {
        headers = {
          Authorization: 'Bearer ' + access_token,
          'X-Tenant': getUserInfo().HotelId
        }
      }

      if (mergeHeaders) {
        headers = { ...headers, ...mergeHeaders }
      }

      if (url !== '/WeApp/ValidCode' && url !== '/WeApp/Login') {
        // 不为请求验证码的时候，不然错误提示会被下一次请求的loading刷掉
        uni.showLoading({
          title: '',
          mask: true
        })
      }

      if (method === 'DELETE' || method === 'delete') {
        if (Object.keys(data).length > 0) {
          let count = 0
          for (let key in data) {
            const value: string = data[key]
            if (count === 0) {
              url = url + '?' + key + '=' + value
            } else {
              url = url + '&' + key + '=' + value
            }
            count++
          }
          data = null
          //   如果是del请求，有参数会自动拼接url，拼接完了就
        }
      }
      uni.request({
        header: headers,
        url: baseURL + url,
        // @ts-ignore
        method,
        data,
        success(response) {
          const res: resType = response.data as resType // 断言为resType
          const { Code, Result, Message } = res
          if (Code === 1000) {
            if (url === '/WeApp/ChangePwd') {
              resolve(Message)
            } else resolve(Result)
          } else if (Code === 401) {
            handler_401(platform)
          } else {
            if (url === '/WeApp/Login' && platform === 'server') {
              //   这个登录服务端的Result才是 Message的错误提示，需要单独处理
              handler_WeAppLogin_4000(Result, Code, Message)
            } else {
              // 其余的正常报错Message, 当然了，3000也报错
              toast.$toast(Message)
            }
            reject(Message)
          }
        },
        fail(err) {
          toast.$toast('服务响应失败')
          reject(err)
        },
        complete() {
          if (url !== '/WeApp/ValidCode' && url !== '/WeApp/Login') {
            uni.hideLoading()
          }
        }
      })
    })
  }
}
// 全局请求封装

export default createRequest
